import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from "axios"
import { useUserStore } from '@/stores/user'
import { ElMessage,ElLoading } from 'element-plus'
import qs from "qs"

const service: AxiosInstance = axios.create({
        // baseURL: import.meta.env.VITE_BASE_URL_API + import.meta.env.VITE_API_URL ,
  baseURL: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL ,
  timeout: 0,
  withCredentials: false, // 禁用 Cookie 等信息
})

let loading: ReturnType<typeof ElLoading.service> | null = null

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 插入用户凭证
    let token = localStorage.getItem("token")
    const isToken = (config.headers || {}).isToken === false
    if (token && !isToken) {
      config.headers.Authorization = "Bearer " + token
    }

    // 部分接口请求添加loading
    // 在headers里设置false是boolean，而true返回的是string
    const isLoading = (config.headers || {}).loading === "true"
    if (isLoading) loading = ElLoading.service({ text: "loading..." })

    // 过滤掉【null、undefined、""、[]】字段参数
    // const isFilter = (config.headers || {}).filter === false
    // if (!isFilter) {
    //   if (config.params && Object.prototype.toString.call(config.params) === '[object Object]') config.params = filterEmptyValue(config.params)
    //   if (config.data && Object.prototype.toString.call(config.data) === '[object Object]') config.data = filterEmptyValue(config.data)
    // }

    // get参数编码
    const params = config.params || {}
    if (config.method?.toUpperCase() === "GET" && params) {
      config.params = {}
      const paramsStr = qs.stringify(params, { allowDots: true })
      if (paramsStr) config.url = config.url + "?" + paramsStr
    }

    return config
  },
  (error: AxiosError) => {
    Promise.reject(error)
  }
)

const filterEmptyValue = <T extends Record<string, any>>(obj: T): Partial<T> => {
  const isObject = (value: any) => value && typeof value === 'object' && !Array.isArray(value)
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (isObject(value)) {
      // 如果值是对象，则递归调用 filterEmptyValue 并检查返回的结果是否为空
      const filteredValue = filterEmptyValue(value)
      if (Object.keys(filteredValue).length > 0) {  // 只有当过滤后的对象不为空时才添加到结果中
        (acc as any)[key] = filteredValue
      }
    } else if (![null, undefined, ""].includes(value) && !(Array.isArray(value) && value.length === 0)) {
      // 对于非对象类型的值，直接按原逻辑判断
      (acc as any)[key] = value
    }
    return acc
  }, {} as Partial<T>)
}

service.interceptors.response.use(
  async (response: AxiosResponse<any>) => {
    loading?.close()

    const { code, msg, type } = response.data
    const  user = useUserStore()

    // 处理二进制数据文件下载
    const responseType = response.request.responseType
    if (responseType === "blob" || responseType === "arraybuffer") {
      if (type === "application/json") {
        fileReaderError(response.data)
        return Promise.reject("Download Error")
      }
      return Promise.resolve(response.data)
    }

    if (code === "401") {
      ElMessageBox.alert("登录状态已过期，请重新登录", "提示", {
        type: "warning",
        callback: () => user.logout()
      })
      return Promise.reject(response)
    } else if (code != "200") {
      ElMessage({ message: msg, type: "error", plain: true })
      return Promise.reject(response)
    }
    return Promise.resolve(response.data)
  },
  (error: AxiosError) => {
    loading?.close()
    const { message, response } = error as any
    const errorMessage = response?.data?.message || message
    ElMessage({ message: errorMessage, type: "error", plain: true })
    return Promise.reject(error)
  }
)

const fileReaderError = (data: Blob) => {
  const reader = new FileReader()
  reader.readAsText(data)
  reader.onload = (event: ProgressEvent<FileReader>) => {
    const result = event.target?.result
    if (typeof result === "string") {
      const parsedResult = JSON.parse(result)
      ElMessage({ message: parsedResult.msg, type: "error", plain: true })
    }
  }
}

export default service as any
